package com.ruoyi.framework.interceptor;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 通过 Spring 的拦截器（HandlerInterceptor）拦截文件上传请求，
 * 在请求处理完成后触发回调，适合全局统一处理（如所有上传操作的日志记录）
 * */
public class FileUploadInterceptor implements HandlerInterceptor {
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
        // 判断是否为文件上传请求
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            List<MultipartFile> files = multipartRequest.getFiles("file"); // "file" 对应前端参数名

            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    // 执行回调逻辑
                    System.out.println("【拦截器回调】-[文件上传完成]- 文件名:'" + file.getOriginalFilename() + "'");
                    // 其他操作：如校验文件MD5、触发消息队列等
                }
            }
        }
    }
}
